package org.luosl.webmagicx.monitor.action

import java.util.concurrent.ConcurrentHashMap

import org.luosl.webmagicx.SpiderCell
import org.luosl.webmagicx.monitor.{HttpSpiderMonitor, JsonResult, MonitorCell}

import scala.collection.JavaConverters._
import play.api.libs.json.{JsObject, Json}
import us.codecraft.webmagic.Spider.Status
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route

case class SystemAction(monitor:HttpSpiderMonitor) {

  private val monitorCellMap:ConcurrentHashMap[String,MonitorCell] = monitor.monitorCellMap
  /**
    * 获取系统概览
    * @return
    */
  def overview():Route = {
    val monitorCell:Iterable[MonitorCell] = monitorCellMap.values().asScala
    val spiders:Iterable[SpiderCell] = monitorCell.map(_.spiderCell)
    val json:JsObject = Json.obj(
      "allSpiderCount" -> monitorCellMap.size(),
      "runningCount" -> spiders.count(_.status() == Status.Running),
      "spiders" -> monitorCell.map{ cell=>
        val spiderCell = cell.spiderCell
        Json.obj(
          "id" -> spiderCell.id,
          "desc" -> spiderCell.sc.desc,
          "status" -> spiderCell.status().toString,
          "taskType" -> spiderCell.sc.taskType,
          "runTime" -> cell.spiderListener.runTime
        )
      }
    )
    complete(HttpEntity(ContentTypes.`application/json`, JsonResult.success(json).jsStr))
  }

  /**
    * 终止系统
    * @return
    */
  def shutdown():Route = {
    monitor.shutdown()
    complete(HttpEntity(ContentTypes.`application/json`, JsonResult.success("shutdown success").jsStr))
  }

}
